package com.example.mqdemo.springmq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class RabbitMqConfig {
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory("10.15.9.113");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("SCM_SYN");
        return factory;
    }

//    @Bean
//    public AmqpAdmin amqpAdmin() {
//        return new RabbitAdmin(connectionFactory());
//    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        return new RabbitTemplate(connectionFactory());
    }


    @Bean
    public ApplicationRunner runner(AmqpTemplate template) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "ckl");
        map.put("age",20);

        return args -> template.convertAndSend("CAD_1234", map);
    }



    @RabbitListener(queues = "CAD_1234")
    public void listen(String in) {
        log.info("receive {}", in);
    }


    @RabbitListener(queues = "myqueue")
    public void listenmyqueue(Message message) {
        System.out.println("====消费消息===handleMessage(message)");
        System.out.println(message.getMessageProperties());
        System.out.println(new String(message.getBody()));
    }


    @Bean
    public Queue cadCurrentCenterQueue() {
        Map<String, Object> arguments = new HashMap<String, Object>();
        arguments.put("x-single-active-consumer", true);
        arguments.put("x-queue-type", "classic");
        Queue queue = new Queue("CAD_1234" ,true,false,false,arguments);

        return queue;
    }

    @Bean
    public Queue myqueue() {
        Map<String, Object> arguments = new HashMap<String, Object>();
        arguments.put("x-single-active-consumer", true);
        arguments.put("x-queue-type", "classic");
        Queue queue = new Queue("myqueue" ,true,false,false,arguments);

        return queue;
    }
}
